'use strict';

var model = require('../../model/thread.js');
var debug = require('debug')('dao_thread_impl');
var appUtils = require('../../common/app_utils.js');
var errInfo = require('../../common/err_info.js');
var md5 = appUtils.md5;
var fout = appUtils.formatOutput;
var ferror = appUtils.formatError;

function DaoImpl() {
	var self = this instanceof DaoImpl ? this : new DaoImpl();
	return self;
}

module.exports = new DaoImpl();
var theProto = DaoImpl.prototype;

// create a thread
theProto.create = function(json) {
	debug('create ', json);
	// TODO check, if userId available
	var item = new model({
		userId: json.userId,
		title: json.title,
		content: json.content
	});

	return item.save()
		.then(function(result) {
			return fout(result);
		}, function(err) {
			return ferror(errInfo.E1000, 'mongodb error: ' + err.errmsg);
		});
};

// json: {query:q, limit:l, skip:s, projection:p, sort:s}
theProto.read = function(json) {
	return model.find(json.query, json.projection || __defaultProject)
		.limit(json.limit)
		.skip(json.skip)
		.sort(json.sort)
		.exec()
		.then(function(result) {
			return fout(result);
		}, function(err) {
			return ferror(errInfo.E1000, 'mongodb error: ' + err.errmsg);
		})
};

var __defaultProject = {
	// _id: 0,
	__v: 0
};